// ../cms-js-internal/dist/types-BoToPcXg.js
import path from "path";
import { createHash } from "crypto";
import fs, { readFileSync, existsSync, readdirSync, lstatSync } from "fs";
import { join } from "path/posix";
var COMPONENT_EXTENSIONS = [".jsx", ".tsx", ".js", ".ts"];
var ENTRY_POINTS_PATH = "components/partials/";
var MODULE_FOLDER_PATH = "components/modules/";
var TEMPLATE_FOLDER_PATH = "components/templates/";
var VIRTUAL_ISLAND_RUNTIME = "virtual:island-runtime";
var VIRTUAL_CONFIG_SETUP = "virtual:config-setup";
var CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
var collectCssModules = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
  const appModulesForPath = viteServer.moduleGraph.fileToModulesMap.get(
    modulePathToStartWith
  );
  if (!appModulesForPath || appModulesForPath.size === 0) {
    throw new Error(`No modules at: ${modulePathToStartWith}`);
  } else if (appModulesForPath.size > 1) {
    throw new Error(`More than one module at: ${modulePathToStartWith}`);
  }
  const appModule = Array.from(appModulesForPath.values())[0];
  const allServerSideModulesImported = /* @__PURE__ */ new Set();
  const newCssModules = [];
  const moduleQueue = Array.from(appModule.importedModules);
  for (const importedModule of moduleQueue) {
    if (allServerSideModulesImported.has(importedModule.id)) {
      continue;
    }
    allServerSideModulesImported.add(importedModule.id);
    const isCss = CSS_LANGS_RE.test(importedModule.file);
    const moduleModulesToQueue = Array.from(importedModule.importedModules);
    if (isCss && !cssModulesImported.has(importedModule)) {
      cssModulesImported.add(importedModule);
      newCssModules.push(importedModule);
    }
    moduleQueue.push(...moduleModulesToQueue);
  }
  return newCssModules;
};
function createPreloadLink(assetPath, basePath = "") {
  if (assetPath && assetPath[0] !== "/") {
    assetPath = `/${assetPath}`;
  }
  if (assetPath.endsWith(".js")) {
    return `<link rel="modulepreload" crossorigin href="${basePath}${assetPath}">`;
  } else if (CSS_LANGS_RE.test(assetPath)) {
    return `<link rel="stylesheet" href="${basePath}${assetPath}?css">`;
  } else if (assetPath.endsWith(".woff")) {
    return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff" crossorigin>`;
  } else if (assetPath.endsWith(".woff2")) {
    return ` <link rel="preload" href="${basePath}${assetPath}" as="font" type="font/woff2" crossorigin>`;
  } else if (assetPath.endsWith(".gif")) {
    return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/gif">`;
  } else if (assetPath.endsWith(".jpg") || assetPath.endsWith(".jpeg")) {
    return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/jpeg">`;
  } else if (assetPath.endsWith(".png")) {
    return ` <link rel="preload" href="${basePath}${assetPath}" as="image" type="image/png">`;
  } else {
    throw new Error(`Unknown preload type for ${assetPath}`);
  }
}
var collectCssInDev = (modulePathToStartWith, viteServer, cssModulesImported = /* @__PURE__ */ new Set()) => {
  return `${collectCssModules(
    modulePathToStartWith,
    viteServer,
    cssModulesImported
  ).map((cssModule) => createPreloadLink(cssModule.url)).join("\n")}
`;
};
function sortKeys(input, options = {}) {
  const { deep, compare } = options;
  const cache = /* @__PURE__ */ new WeakMap();
  function deepSortArray(array) {
    const resultFromCache = cache.get(array);
    if (resultFromCache !== void 0) {
      return resultFromCache;
    }
    const result = [];
    cache.set(array, result);
    result.push(
      ...array.map((item) => {
        if (Array.isArray(item)) {
          return deepSortArray(item);
        }
        if (isPlainObject(item)) {
          return _sortKeys(item);
        }
        return item;
      })
    );
    return result;
  }
  function _sortKeys(object) {
    const resultFromCache = cache.get(object);
    if (resultFromCache !== void 0) {
      return resultFromCache;
    }
    const result = {};
    const keys = Object.keys(object).sort(compare);
    cache.set(object, result);
    for (const key of keys) {
      const value = object[key];
      let newValue;
      if (deep && Array.isArray(value)) {
        newValue = deepSortArray(value);
      } else {
        newValue = deep && isPlainObject(value) ? _sortKeys(value) : value;
      }
      Object.defineProperty(result, key, {
        ...Object.getOwnPropertyDescriptor(object, key),
        value: newValue
      });
    }
    return result;
  }
  if (Array.isArray(input)) {
    return deep ? deepSortArray(input) : [...input];
  }
  return _sortKeys(input);
}
function isPlainObject(value) {
  if (typeof value !== "object" || value === null) {
    return false;
  }
  const prototype = Object.getPrototypeOf(value);
  return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
}
var badInlineJsChars = /[\u2028\u2029<>/]/g;
var inlineJsEscapeChars = {
  "\u2028": "\\u2028",
  "\u2029": "\\u2029",
  "<": "\\u003C",
  ">": "\\u003E",
  "/": "\\u002F"
};
function escapeChar(unsafeChar) {
  return inlineJsEscapeChars[unsafeChar];
}
function escapeForInlineJS(input) {
  return input.replace(badInlineJsChars, escapeChar);
}
function jsonStringifyAndEscapeForInlineJS(input, { baseIndent = 0, jsonIndent = 2, prettyPrint = true } = {}) {
  const indentString = " ".repeat(baseIndent);
  jsonIndent = prettyPrint ? jsonIndent : void 0;
  let sorted;
  try {
    if (isPlainObject(input) || Array.isArray(input)) {
      sorted = sortKeys(input, { deep: true });
    }
  } catch (e) {
    console.error("Error sorting Island keys", e);
  }
  return escapeForInlineJS(
    JSON.stringify(sorted ?? input, null, jsonIndent)
  ).replace(/\n/gm, `
${indentString}`);
}
var viteRoot;
var viteCommand;
function resolveIslandPlugin(islandsSet) {
  return {
    enforce: "pre",
    name: "resolve-islands",
    configResolved(config) {
      viteRoot = config.root;
      viteCommand = config.command;
    },
    load(id) {
      if (id.endsWith("?island") || id.endsWith("?client")) {
        const [idWithNoParam] = id.split("?");
        const islandModuleImportPath = `${idWithNoParam}?client-entry`;
        const componentExtension = path.extname(idWithNoParam);
        const componentFilenameWithNoExtension = path.basename(
          idWithNoParam,
          componentExtension
        );
        const modulePath = path.relative(viteRoot, idWithNoParam);
        const moduleId = (viteCommand === "serve" ? idWithNoParam : modulePath).concat("?client-entry");
        if (islandsSet) {
          islandsSet.add(moduleId);
        }
        return `
            const moduleId = '${moduleId}';

            const lazyComponent = () => import('${islandModuleImportPath}');
            lazyComponent.moduleName = '${componentFilenameWithNoExtension}';
            lazyComponent.moduleId = moduleId;

            export default lazyComponent;
          `;
      }
      return null;
    }
  };
}
function resolveIslandToPlainModulePlugin(enabled = true) {
  return {
    enforce: "pre",
    name: "resolve-islands-to-plain",
    configResolved(config) {
      viteRoot = config.root;
      viteCommand = config.command;
    },
    async resolveId(id, importer, options) {
      if (enabled && (id.endsWith("?island") || id.endsWith("?client"))) {
        const newId = id.replace("?island", "").replace("?client", "");
        const resolution = await this.resolve(newId, importer, {
          skipSelf: true,
          ...options
        });
        if (resolution) {
          return resolution;
        }
      }
      return null;
    }
  };
}
function resolveIslandToPlainModuleNoopPlugin() {
  return resolveIslandToPlainModulePlugin(false);
}
var clientRenderIsland = "import type { RenderableIsland } from '@hubspot/cms-components';\nimport * as cmsComponents from '@hubspot/cms-components';\nimport { ClientRenderContextProvider } from '@hubspot/cms-components';\nimport { Suspense } from 'react';\nimport ReactDOMClient from 'react-dom/client';\n\nconst buildIslandIdentifierPrefix =\n  cmsComponents.buildIslandIdentifierPrefix || ((id) => id);\n\nexport function clientRenderIsland(\n  renderableIsland: RenderableIsland,\n  Component: React.ComponentType<any>\n) {\n  const {\n    island,\n    rootElement,\n    postHydration,\n    pageUrl,\n    islands,\n    basePath,\n    WrapperModule,\n  } = renderableIsland;\n  let reactRoot: any;\n\n  const rootOptions = {\n    // Ensure useId is unique across island roots\n    identifierPrefix: buildIslandIdentifierPrefix(renderableIsland.island.id),\n  };\n\n  let innerComponent = <Component islandId={island.id} {...island.props} />;\n  if (WrapperModule) {\n    innerComponent = <WrapperModule>{innerComponent}</WrapperModule>;\n  }\n\n  const elementsToHydrate = (\n    <Suspense fallback={`client hydrate fail/waiting for ${island.id}`}>\n      <ClientRenderContextProvider\n        pageUrl={pageUrl}\n        islands={islands}\n        onTopLevelHydrationFinish={postHydration}\n        island={island}\n        basePath={basePath}\n      >\n        {innerComponent}\n      </ClientRenderContextProvider>\n    </Suspense>\n  );\n\n  if (island.clientOnly) {\n    reactRoot = ReactDOMClient.createRoot(rootElement, rootOptions);\n    reactRoot.render(elementsToHydrate);\n  } else {\n    reactRoot = ReactDOMClient.hydrateRoot(\n      rootElement,\n      elementsToHydrate,\n      rootOptions\n    );\n  }\n  return reactRoot;\n}\n";
var virtualClientRenderIslandModuleId = "virtual:clientRenderIsland.tsx";
function clientIslandEntryPlugin() {
  return {
    enforce: "pre",
    name: "client-island-entry-plugin",
    resolveId(id) {
      if (id === virtualClientRenderIslandModuleId) {
        return virtualClientRenderIslandModuleId;
      }
      return null;
    },
    load(id) {
      if (id.endsWith("?client-entry")) {
        const [idWithNoParam] = id.split("?");
        return `
            import { clientRenderIsland } from '${virtualClientRenderIslandModuleId}';
            import Component from '${idWithNoParam}';

            export function render(island) {
              return clientRenderIsland(island, Component)
            }

            export default Component;
          `;
      }
      if (id === virtualClientRenderIslandModuleId) {
        return clientRenderIsland;
      }
      return null;
    }
  };
}
var scriptTagToLogServerMessages = (messagesForBrowser, groupLabel, nonceAttribute) => {
  if (!messagesForBrowser) {
    return "";
  }
  const consoleLines = [];
  for (const message of messagesForBrowser) {
    let funcString = "console.log";
    if (message.level === "error") {
      funcString = "console.error";
    }
    if (message.level === "warn") {
      funcString = "console.warn";
    }
    const argString = message.parameters.map((arg) => JSON.stringify(arg)).join(", ");
    consoleLines.push(`  ${funcString}(${argString});`);
  }
  let groupStart = "";
  let groupEnd = "";
  if (groupLabel !== void 0 && groupLabel !== null) {
    groupStart = `
  console.group(${JSON.stringify(groupLabel)});`;
    groupEnd = `  console.groupEnd()
`;
  }
  return `<script ${nonceAttribute}>${groupStart}
${consoleLines.join("\n")}
${groupEnd}</script>
`;
};
var getComponentExtension = (componentPath) => {
  const filteredExtensions = COMPONENT_EXTENSIONS.filter(
    (ext) => componentPath.endsWith(ext)
  );
  if (filteredExtensions.length === 1) {
    return filteredExtensions[0];
  }
  return void 0;
};
var hasComponentExtension = (componentPath) => {
  return !!getComponentExtension(componentPath);
};
var isStorybookStory = (componentPath) => {
  return !!path.basename(componentPath, path.extname(componentPath)).endsWith(".stories");
};
var removeComponentExtension = (componentPath) => {
  const ext = getComponentExtension(componentPath);
  if (ext == null) {
    return componentPath;
  }
  return componentPath.slice(0, -1 * ext.length);
};
function getEntryPointHash(entryPoint) {
  return createHash("md5").update(entryPoint).digest("hex").slice(0, 6);
}
function getEntryPointHashWithIndexSuffix(entryPoint, index) {
  const renderIndexSuffix = index != null ? `i${index}` : "";
  return `${getEntryPointHash(entryPoint)}${renderIndexSuffix}`;
}
var COMBINED_REACT_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/react/v18";
var ISLAND_RUNTIME_CONFIG_BASE_PATH = "https://static.hsappstatic.net/cms-js-static/ex/js/island-runtime/v1";
function getCombinedReactUrl() {
  const hsEnv = process.env.HS_ENV;
  const fileVersion = hsEnv === "prod" ? `react-combined.mjs` : "react-combined-qa.mjs";
  return `${COMBINED_REACT_BASE_PATH}/${fileVersion}`;
}
function getIslandRuntimeConfigUrl() {
  const hsEnv = process.env.HS_ENV;
  const fileVersion = hsEnv === "prod" ? `island-runtime.mjs` : "island-runtime-qa.mjs";
  return `${ISLAND_RUNTIME_CONFIG_BASE_PATH}/${fileVersion}`;
}
function includesHublDataReference(templateSource) {
  const hublDataPattern = /\{%\s+set\s+(experimentalHublData|hublData)\s*=/;
  return !!templateSource.match(hublDataPattern);
}
var removeIndexFromPath = (id) => {
  return id.replace(/\/index\.[jt]sx?$/, "");
};
var removeIndexOrTrailingJsFromPath = (id) => {
  return removeIndexFromPath(id).replace(/\.[jt]sx?$/, "");
};
var HEALTHCHECKS_ENABLED_DEFAULT = true;
var HEALTHCHECKS_STRICT_DEFAULT = false;
function getCMSAssetConfig(webRoot) {
  const cmsAssetsPath = path.join(webRoot, "cms-assets.json");
  const cmsThemePath = path.join(webRoot, "theme.json");
  const configPathToUse = fs.existsSync(cmsAssetsPath) ? cmsAssetsPath : cmsThemePath;
  const parsedConfig = JSON.parse(
    fs.readFileSync(configPathToUse).toString()
  );
  return parsedConfig;
}
function getCMSAssetConfigIfExists(webRoot) {
  try {
    return getCMSAssetConfig(webRoot);
  } catch (e) {
    console.error(
      `Error finding or parsing cms-assets.json in ${webRoot}, but ignoring for now`
    );
    return {};
  }
}
function areBuildHealthChecksEnabled(config) {
  var _a, _b;
  return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.enabled) ?? HEALTHCHECKS_ENABLED_DEFAULT;
}
function doHealthChecksFailTheBuild(config) {
  var _a, _b;
  return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.healthchecks) == null ? void 0 : _b.strict) ?? HEALTHCHECKS_STRICT_DEFAULT;
}
function getServerIncludePrebundleDepPatterns(config) {
  var _a, _b;
  return ((_b = (_a = config.buildConfig) == null ? void 0 : _a.serverPrebundling) == null ? void 0 : _b.include) ?? [];
}
var BUILD_INFO_PATH = "/build-info.json";
function getBuildInfo(buildDir) {
  try {
    const buildInfo = JSON.parse(
      readFileSync(path.join(buildDir, BUILD_INFO_PATH)).toString()
    );
    return buildInfo;
  } catch (e) {
    throw new Error(`Error loading build-info.json, path: ${BUILD_INFO_PATH}`);
  }
}
function getBaseAssetUrlFromBuild(buildDir) {
  return getBuildInfo(buildDir).baseAssetUrl;
}
var GATES = [
  "CMS:JSRenderer:GetServerSideProps",
  "CMS:JSRenderer:ModuleHubl",
  "CMS:JSRenderer:RemoveCjsPlugin",
  "CMS:JSRenderer:RemoveMockClientEntryPlugin",
  "CMS:JSRenderer:AnalyzeCmsModules",
  "CMS:JSRenderer:StripNullBytes"
];
var ENABLED_FEATURES_GATE_MAP = {
  "cms:jsr:getServerSideProps": "CMS:JSRenderer:GetServerSideProps",
  "cms:jsr:RemoveCjsPlugin": "CMS:JSRenderer:RemoveCjsPlugin",
  "cms:jsr:analyzeCmsModules": "CMS:JSRenderer:AnalyzeCmsModules"
};
function isUngatedFor(gates, gate) {
  return gates.includes(gate);
}
function ungatedAtBuildTimeFor(buildDir, gate) {
  try {
    const buildInfo = getBuildInfo(buildDir);
    return isUngatedFor(buildInfo.gates, gate);
  } catch (e) {
    return false;
  }
}
var findAllComponentsIn = (webRoot, componentsFolder) => {
  const fullComponentsFolderPath = join(webRoot, componentsFolder);
  const componentsByName = {};
  if (!existsSync(fullComponentsFolderPath)) {
    return componentsByName;
  }
  readdirSync(fullComponentsFolderPath).forEach((fileOrFolderName) => {
    const fullPath = join(fullComponentsFolderPath, fileOrFolderName);
    const subdirPath = join(componentsFolder, fileOrFolderName);
    const isDirectory = lstatSync(fullPath).isDirectory();
    if (!isDirectory && hasComponentExtension(fileOrFolderName) && !isStorybookStory(fileOrFolderName)) {
      const subdirPathNoExtension = removeComponentExtension(subdirPath);
      componentsByName[subdirPathNoExtension] = subdirPath;
    } else if (isDirectory) {
      for (const potentialExtension of COMPONENT_EXTENSIONS) {
        const potentialIndexModule = join(
          subdirPath,
          `index${potentialExtension}`
        );
        const fullPotentialPath = join(
          fullPath,
          `index${potentialExtension}`
        );
        if (existsSync(fullPotentialPath)) {
          const moduleIndexPathNoExtension = removeComponentExtension(potentialIndexModule);
          componentsByName[moduleIndexPathNoExtension] = potentialIndexModule;
          break;
        }
      }
    }
  });
  return componentsByName;
};
function findAllModulesInRoot(webRoot) {
  const allModuleComponents = findAllComponentsIn(
    webRoot,
    "./components/modules"
  );
  const moduleNames = Object.keys(allModuleComponents).map(
    (moduleSubpath) => moduleSubpath.replace("components/modules/", "").replace("/index", "")
  );
  const moduleSubpaths = Object.keys(allModuleComponents);
  const moduleExtensions = Object.values(allModuleComponents).map((path2) => {
    if (!path2)
      return "";
    const extension = path2.split(".").pop() || "";
    return extension;
  });
  const moduleNamesWithExtension = Object.values(allModuleComponents).map(
    (path2) => {
      if (!path2)
        return "";
      const file = path2.replace("components/modules/", "");
      return file.includes("/index.") ? file.split("/index.")[0] : file;
    }
  );
  return {
    moduleNames,
    moduleSubpaths,
    moduleNamesWithExtension,
    moduleExtensions
  };
}
function findAllPartialsInRoot(webRoot) {
  const allPartialComponents = findAllComponentsIn(
    webRoot,
    "./components/partials"
  );
  const partialNames = Object.keys(allPartialComponents).map(
    (partialSubpath) => partialSubpath.replace("components/partials/", "").replace("/index", "")
  );
  const partialSubpaths = Object.keys(allPartialComponents);
  return { partialNames, partialSubpaths };
}
function namespaceModulePropsShape(props) {
  const {
    dataQueryResult,
    hublParameters,
    fieldValues: passedFieldValues,
    hublData,
    experimentalHublData,
    moduleName,
    supplementalFieldValues
  } = props;
  const oldPropsShape = { ...props };
  if (oldPropsShape.dataQueryResult) {
    delete oldPropsShape.dataQueryResult;
  }
  if (oldPropsShape.hublParameters) {
    delete oldPropsShape.hublParameters;
  }
  const fieldValues = passedFieldValues || oldPropsShape;
  return {
    ...fieldValues,
    dataQueryResult,
    fieldValues,
    hublParameters,
    hublData,
    experimentalHublData,
    moduleName,
    supplementalFieldValues
  };
}
function setIn(object, nestedKeysArray, value) {
  let curr = object;
  const finalKey = nestedKeysArray.pop();
  for (let index = 0; index < nestedKeysArray.length; index++) {
    const currentKey = nestedKeysArray[index];
    const nextKey = nestedKeysArray[index + 1];
    if (Number.isInteger(nextKey) || !nextKey && Number.isInteger(finalKey)) {
      if (curr[currentKey] === void 0) {
        curr[currentKey] = [];
      }
    }
    if (curr[currentKey] === void 0) {
      curr[currentKey] = {};
    }
    curr = curr[currentKey];
  }
  if (value !== void 0) {
    curr[finalKey] = value;
  }
}
function isStylesheetAsset(staticAsset) {
  return staticAsset.type === "stylesheet";
}

// ../cms-js-internal/dist/index.js
import * as dotProp from "dot-prop";
import * as parser from "@babel/parser";
import _traverse from "@babel/traverse";
import * as t from "@babel/types";
import { jsx } from "react/jsx-runtime";
import stream from "stream";
import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
import * as cmsComponents from "@hubspot/cms-components";
import { ServerRenderContext } from "@hubspot/cms-components";
import { isValidElement, cloneElement } from "react";
var { setProperty, getProperty, hasProperty } = dotProp;
var serializeIslandDataForInlineScript = (tweakedIslandsArray, perServerRequestData, baseIndent = 0, prettyPrint) => {
  const islandsArrayToSerialize = tweakedIslandsArray.map(
    ({
      id,
      moduleName,
      moduleId,
      props,
      hydrateOn,
      clientOnly,
      priority,
      url,
      sharedStateID,
      supplementalFieldValues,
      wrapperModuleId,
      wrapperUrl,
      resolvedDataDependencies
    }) => {
      const output = {
        id,
        moduleName,
        moduleId,
        hydrateOn,
        clientOnly,
        priority,
        props,
        url
      };
      if (resolvedDataDependencies) {
        output.resolvedDataDependencies = resolvedDataDependencies;
      }
      if (sharedStateID) {
        output.sharedStateID = sharedStateID;
      }
      if (wrapperModuleId) {
        output.wrapperModuleId = wrapperModuleId;
      }
      if (wrapperUrl) {
        output.wrapperUrl = wrapperUrl;
      }
      const filteredSupplementalFieldValues = filterOutUnreadSupplementalFieldValues(
        supplementalFieldValues,
        perServerRequestData.get("supplementalFieldValuesRead")
      );
      if (filteredSupplementalFieldValues) {
        output.supplementalFieldValues = filteredSupplementalFieldValues;
      }
      if (output.clientOnly) {
        output.supplementalFieldValues = supplementalFieldValues;
      }
      return output;
    }
  );
  return jsonStringifyAndEscapeForInlineJS(islandsArrayToSerialize, {
    baseIndent,
    jsonIndent: 2,
    prettyPrint
  });
};
function filterOutUnreadSupplementalFieldValues(supplementalFieldValues, supplementalFieldValuesRead) {
  if (!supplementalFieldValues) {
    return supplementalFieldValues;
  }
  if (!supplementalFieldValuesRead) {
    return supplementalFieldValues;
  }
  const result = {};
  Array.from(supplementalFieldValuesRead).forEach((fieldPath) => {
    if (hasProperty(supplementalFieldValues, fieldPath)) {
      setProperty(
        result,
        fieldPath,
        getProperty(supplementalFieldValues, fieldPath)
      );
    }
  });
  return result;
}
var writeSharedStateToJsGlobal = (islands, perServerRequestData, indent = 0, prettyPrint) => {
  const sharedStateIDs = islands.map((island) => island.sharedStateID).filter((x2) => !!x2);
  if (sharedStateIDs.length > 0) {
    const indentString = " ".repeat(indent);
    const stateByID = {};
    sharedStateIDs.forEach(
      (id) => stateByID[id] = perServerRequestData.get(id)
    );
    const stringifiedState = jsonStringifyAndEscapeForInlineJS(stateByID, {
      prettyPrint,
      jsonIndent: 2
    });
    return `

var newState = ${stringifiedState};
if(window.__hsSSInit) {
  window.__hsSSInit = Object.assign(window.__hsSSInit, newState);
} else {
  window.__hsSSInit = newState;
}`.replace(/\n/gm, `
${indentString}`);
  }
  return "";
};
function getIslandUrls(roots, viteDevServer) {
  return roots.map((island) => {
    const islandModule = viteDevServer.moduleGraph.getModuleById(
      island.moduleId
    );
    if (!islandModule) {
      throw new Error(`Unknown island moduleId: ${island.moduleId}`);
    }
    let wrapperModule;
    if (island.wrapperModuleId) {
      wrapperModule = viteDevServer.moduleGraph.getModuleById(
        island.wrapperModuleId
      );
    }
    const tweakedIsland = {
      ...island,
      url: islandModule.url,
      wrapperUrl: wrapperModule ? wrapperModule.url : void 0
    };
    return tweakedIsland;
  });
}
function getPerServerRequestUrls(perServerRequestData, viteDevServer) {
  if (!perServerRequestData.has("sharedStateIDs")) {
    return new Map(perServerRequestData);
  }
  const perServerRequestDataWithUrls = new Map(
    perServerRequestData
  );
  perServerRequestData.get("sharedStateIDs").forEach((id) => {
    const reducer = perServerRequestData.get(id);
    if (reducer.reducerFuncModuleId) {
      const reducerWithUrl = {
        ...reducer,
        reducerFuncModuleUrl: viteDevServer.moduleGraph.getModuleById(
          reducer.reducerFuncModuleId
        ).url
      };
      perServerRequestDataWithUrls.set(id, reducerWithUrl);
    }
  });
  return perServerRequestDataWithUrls;
}
var createIslandsGlobalJsForClientInDev = (roots, perServerRequestData, viteDevServer, indent, prettyPrint) => {
  const islands = getIslandUrls(roots, viteDevServer);
  const perServerRequestDataWithUrls = getPerServerRequestUrls(
    perServerRequestData,
    viteDevServer
  );
  return `${" ".repeat(
    indent
  )}window.__islands = ${serializeIslandDataForInlineScript(
    islands,
    perServerRequestData,
    indent,
    prettyPrint
  )}${writeSharedStateToJsGlobal(
    islands,
    perServerRequestDataWithUrls,
    indent,
    prettyPrint
  )}`;
};
function noncePlaceholderPlugin() {
  const HS_DEPLOYED = process.env.AWS_EXECUTION_ENV != null || process.env.HS_DEPLOYED === "true";
  return {
    name: "hs-nonce-placeholder",
    enforce: "post",
    apply() {
      return HS_DEPLOYED;
    },
    transformIndexHtml(html) {
      const regex = /<(style|script|link) (.*)>/gi;
      const replacer = (_, p1, p2) => {
        if (p1 === "style" || p1 === "script" || // if link, only nonce for stylesheet
        p1 === "link" && p2.includes('rel="stylesheet"')) {
          const noncePlaceholderValue = p1 === "script" ? "hs-random-nonce" : "hs-random-style-nonce";
          p2 = `nonce="${noncePlaceholderValue}" ${p2}`;
        }
        return `<${p1} ${p2}>`;
      };
      return html.replace(regex, replacer);
    }
  };
}
var traverse = _traverse.default;
var CMS_MODULE_COMPONENT_NAME = "Module";
var DND_AREA_COMPONENT_NAME = "DndArea";
var PLUGIN_NAME = "findCmsModules";
function findCmsModules(buildContentDescriptors = {}) {
  let config;
  return {
    enforce: "pre",
    name: "findCmsModules",
    configResolved(resolvedConfig) {
      config = resolvedConfig;
    },
    transform(code, id) {
      const moduleInfo = this.getModuleInfo(id);
      if (!shouldAnalyzeModule(config, moduleInfo, code))
        return null;
      const contentDescriptors = analyzeSourceCodeUsages(
        this,
        moduleInfo,
        config,
        code
      );
      if (Object.keys(contentDescriptors.dndAreas).length > 0 || Object.keys(contentDescriptors.modules).length > 0) {
        return {
          meta: {
            findCmsModules: contentDescriptors
          }
        };
      }
    },
    buildEnd(error) {
      if (error)
        throw error;
      const entryPoints = getEntryPoints(this, config);
      const entryPointCmsModuleMap = buildEntryPointsCmsModuleMap(
        this,
        entryPoints
      );
      const relativeEntryPointCmsModuleMap = convertEntryPointPathsToRelative(
        config,
        entryPointCmsModuleMap
      );
      const entryPointIslandCmsModuleMap = buildEntryPointIslandsCmsModuleMap(
        this,
        entryPoints
      );
      const relativeEntryPointIslandCmsModuleMap = convertEntryPointIslandPathsToRelative(
        config,
        entryPointIslandCmsModuleMap
      );
      if (Object.keys(relativeEntryPointIslandCmsModuleMap).length > 0) {
        this.error(`
          Error: <Module /> cannot be used within <Island />
          Found invalid usages:
          ${JSON.stringify(relativeEntryPointIslandCmsModuleMap, null, 2)}
          `);
      }
      const modulesWithinModules = filterEntryPointsToModules(
        relativeEntryPointCmsModuleMap
      );
      if (Object.keys(modulesWithinModules).length > 0) {
        this.error(`
          Error: <Module /> can only be used in React Partials
          Found invalid usages:
          ${JSON.stringify(modulesWithinModules, null, 2)}
        `);
      }
      Object.assign(buildContentDescriptors, relativeEntryPointCmsModuleMap);
    }
  };
}
function convertEntryPointPathsToRelative(config, entryPointsCmsModuleMap) {
  const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
    ([entryPointPath, cmsModules]) => {
      return [toRelativePath(config, entryPointPath), cmsModules];
    }
  );
  return Object.fromEntries(relativeEntries);
}
function convertEntryPointIslandPathsToRelative(config, entryPointsCmsModuleMap) {
  const relativeEntries = Object.entries(entryPointsCmsModuleMap).map(
    ([entryPointPath, islandContentDescriptors]) => {
      const islandCmsModuleUsage = Object.fromEntries(
        Object.entries(islandContentDescriptors).map(
          ([islandPath, contentDescriptors]) => {
            return [
              toRelativePath(config, islandPath).replace("?client-entry", ""),
              contentDescriptors
            ];
          }
        )
      );
      return [toRelativePath(config, entryPointPath), islandCmsModuleUsage];
    }
  );
  return Object.fromEntries(relativeEntries);
}
function toRelativePath(config, path2) {
  return path2.replace(`${config.root}/`, "");
}
function shouldAnalyzeModule(config, moduleInfo, code) {
  const [fileId, __] = moduleInfo.id.split("?");
  const isExternal = config.command !== "serve" && moduleInfo.isExternal;
  return (
    // analyze customer code only
    !isExternal && moduleInfo.id.startsWith(config.root) && // jsx files that contain "Module" / "DndArea"
    (fileId.endsWith(".tsx") || fileId.endsWith(".jsx")) && (code.includes(CMS_MODULE_COMPONENT_NAME) || code.includes(DND_AREA_COMPONENT_NAME))
  );
}
function getEntryPoints(ctx, config) {
  return Array.from(ctx.getModuleIds()).filter((moduleId) => moduleId.startsWith(config.root)).map((moduleId) => ctx.getModuleInfo(moduleId)).filter((moduleInfo) => moduleInfo.isEntry);
}
function buildEntryPointsCmsModuleMap(ctx, entryPoints) {
  const entryPointCmsModuleUsage = {};
  for (const entryPoint of entryPoints) {
    const result = findCmsModuleUsages(ctx, entryPoint.id);
    if (result) {
      entryPointCmsModuleUsage[entryPoint.id] = result;
    }
  }
  return entryPointCmsModuleUsage;
}
function buildEntryPointIslandsCmsModuleMap(ctx, entryPoints) {
  const entryPointIslandsCmsModuleMap = {};
  for (const entryPoint of entryPoints) {
    const result = findIslandCmsModuleUsage(ctx, entryPoint.id);
    if (result) {
      entryPointIslandsCmsModuleMap[entryPoint.id] = result;
    }
  }
  return entryPointIslandsCmsModuleMap;
}
function analyzeSourceCodeUsages(ctx, moduleInfo, config, code) {
  const sourceAst = parser.parse(code, {
    sourceType: "module",
    plugins: ["jsx", "typescript"]
  });
  const contentDescriptors = { modules: {}, dndAreas: {} };
  let moduleComponentLocalImportName = CMS_MODULE_COMPONENT_NAME;
  let dndAreaComponentLocalImportName = DND_AREA_COMPONENT_NAME;
  traverse(sourceAst, {
    ImportDeclaration(path2) {
      if (t.isStringLiteral(path2.node.source, {
        value: "@hubspot/cms-components"
      })) {
        for (const specifier of path2.node.specifiers) {
          if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
            name: CMS_MODULE_COMPONENT_NAME
          })) {
            moduleComponentLocalImportName = specifier.local.name;
          }
          if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported, {
            name: DND_AREA_COMPONENT_NAME
          })) {
            dndAreaComponentLocalImportName = specifier.local.name;
          }
        }
      }
    },
    JSXOpeningElement(path2) {
      if (t.isJSXIdentifier(path2.node.name, {
        name: moduleComponentLocalImportName
      })) {
        let cmsModuleName;
        let cmsModulePath;
        let cmsModuleLabel;
        for (const prop of path2.node.attributes) {
          if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
            cmsModuleName = prop.value.value;
            continue;
          }
          if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "path" }) && t.isStringLiteral(prop.value)) {
            cmsModulePath = prop.value.value;
            continue;
          }
          if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "label" }) && t.isStringLiteral(prop.value)) {
            cmsModuleLabel = prop.value.value;
            continue;
          }
          ctx.error(
            new Error(
              `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" and "path" must be primitive strings`
            )
          );
        }
        const cmsModuleProps = {
          name: cmsModuleName,
          path: cmsModulePath
        };
        if (cmsModuleLabel) {
          cmsModuleProps.label = cmsModuleLabel;
        }
        if (Object.hasOwn(contentDescriptors.modules, cmsModuleProps.name)) {
          ctx.error(
            new Error(
              `Error: multiple <${CMS_MODULE_COMPONENT_NAME} /> with duplicate name: ${cmsModuleProps.name}`
            )
          );
        }
        contentDescriptors.modules[cmsModuleProps.name] = cmsModuleProps;
      }
      if (t.isJSXIdentifier(path2.node.name, {
        name: dndAreaComponentLocalImportName
      })) {
        let dndAreaName;
        for (const prop of path2.node.attributes) {
          if (t.isJSXAttribute(prop) && t.isJSXIdentifier(prop.name, { name: "name" }) && t.isStringLiteral(prop.value)) {
            dndAreaName = prop.value.value;
            continue;
          }
          ctx.error(
            new Error(
              `Error: ${moduleInfo.id.replace(config.root, "")}:${prop.loc.start.line} "name" must a primitive string`
            )
          );
        }
        const dndArea = {
          name: dndAreaName
        };
        if (Object.hasOwn(contentDescriptors.dndAreas, dndArea.name)) {
          ctx.error(
            new Error(
              `Error: multiple <${DND_AREA_COMPONENT_NAME} /> with duplicate name: ${dndArea.name}`
            )
          );
        }
        contentDescriptors.dndAreas[dndArea.name] = dndArea;
      }
    }
  });
  return contentDescriptors;
}
function findCmsModuleUsages(ctx, moduleId, processed = /* @__PURE__ */ new Set(), result = {}) {
  if (Object.hasOwn(result, moduleId)) {
    return result[moduleId];
  }
  const moduleInfo = ctx.getModuleInfo(moduleId);
  let entryPointContentDescriptors = null;
  if (Object.hasOwn(moduleInfo.meta, PLUGIN_NAME)) {
    entryPointContentDescriptors = {
      ...entryPointContentDescriptors,
      ...moduleInfo.meta[PLUGIN_NAME]
    };
  }
  for (const importedId of [
    ...moduleInfo.importedIds,
    ...moduleInfo.dynamicallyImportedIds
  ]) {
    if (processed.has(importedId)) {
      continue;
    }
    const importedResult = findCmsModuleUsages(
      ctx,
      importedId,
      processed,
      result
    );
    if (importedResult) {
      entryPointContentDescriptors = {
        ...entryPointContentDescriptors,
        ...importedResult
      };
    }
  }
  if (entryPointContentDescriptors) {
    result[moduleId] = entryPointContentDescriptors;
  }
  processed.add(moduleId);
  return entryPointContentDescriptors;
}
function findIslandCmsModuleUsage(ctx, moduleId, processedIslands = /* @__PURE__ */ new Set(), islandModuleResults = {}, processed = /* @__PURE__ */ new Set(), results = {}) {
  processedIslands.add(moduleId);
  if (Object.hasOwn(islandModuleResults, moduleId)) {
    return islandModuleResults[moduleId];
  }
  const moduleInfo = ctx.getModuleInfo(moduleId);
  let resultForModuleId = {};
  if (moduleInfo.id.endsWith("?client-entry")) {
    const mergedDataDependencies = findCmsModuleUsages(
      ctx,
      moduleInfo.id,
      processed,
      results
    );
    if (mergedDataDependencies) {
      resultForModuleId[moduleInfo.id] = mergedDataDependencies;
    }
  }
  for (const importedId of [
    ...moduleInfo.importedIds,
    ...moduleInfo.dynamicallyImportedIds
  ]) {
    if (processedIslands.has(importedId)) {
      continue;
    }
    const importerCmsModuleUsageResult = findIslandCmsModuleUsage(
      ctx,
      importedId,
      processedIslands,
      islandModuleResults,
      processed,
      results
    );
    if (importerCmsModuleUsageResult) {
      resultForModuleId = {
        ...resultForModuleId,
        ...importerCmsModuleUsageResult
      };
    }
  }
  if (Object.keys(resultForModuleId).length > 0) {
    islandModuleResults[moduleId] = resultForModuleId;
    return resultForModuleId;
  }
  return null;
}
function filterEntryPointsToModules(entryPointCmsModuleMap) {
  return Object.fromEntries(
    Object.entries(entryPointCmsModuleMap).filter(
      ([entryPoint]) => entryPoint.startsWith("components/modules/")
    )
  );
}
var promiseForNewWritableStream = () => {
  const chunks = [];
  const writableStream = new stream.Writable();
  writableStream._write = (chunk, encoding, done) => {
    chunks.push(Buffer.from(chunk));
    done();
  };
  const streamDonePromise = new Promise((resolve, reject) => {
    writableStream.on("error", (error) => {
      reject(error);
    });
    writableStream._final = (done) => {
      resolve(Buffer.concat(chunks).toString("utf8"));
      done();
    };
  });
  return { streamDonePromise, writableStream };
};
var renderStreamToPromise = async (reactElements, options) => {
  const { streamDonePromise, writableStream } = promiseForNewWritableStream();
  const {
    pipe
    /* abort */
  } = renderToPipeableStream(reactElements, {
    ...options || {},
    onShellReady() {
    },
    onAllReady() {
      pipe(writableStream);
      if (options == null ? void 0 : options.onAllReady) {
        options.onAllReady();
      }
    }
  });
  return streamDonePromise;
};
var {
  createServerRenderContextV2: createServerRenderContextV22,
  createServerRenderContext: createServerRenderContext2,
  renderServerSidePropsWithAsyncLocalStoreContext
} = cmsComponents;
var bootStrapRenderContext = () => {
  const renderContext = createServerRenderContextV22 ? createServerRenderContextV22(null, {
    environmentConfig: null,
    entryPointBasePath: "",
    supplementalFieldValues: {},
    messagesForBrowser: []
  }) : createServerRenderContext2("", null);
  return renderContext;
};
async function renderComponentOnServer(Component, propsAndDeps, pageUrl, environmentConfig, entryPointBasePath, contextOptions, renderOptions, getServerSideProps) {
  const { props } = propsAndDeps;
  const componentDebugName = Component.displayName || Component.name;
  const supplementalFieldValues = contextOptions == null ? void 0 : contextOptions.supplementalFieldValues;
  const messagesForBrowser = contextOptions == null ? void 0 : contextOptions.messagesForBrowser;
  const renderContext = cmsComponents.createServerRenderContextV2 ? cmsComponents.createServerRenderContextV2(pageUrl, {
    environmentConfig,
    entryPointBasePath,
    supplementalFieldValues,
    messagesForBrowser
  }) : cmsComponents.createServerRenderContext(pageUrl, environmentConfig);
  if (getServerSideProps !== void 0 && typeof getServerSideProps === "function") {
    const gSSPResult = await renderServerSidePropsWithAsyncLocalStoreContext(
      getServerSideProps,
      propsAndDeps,
      renderContext
    );
    if (gSSPResult) {
      props.serverSideProps = gSSPResult.serverSideProps;
    }
  }
  return renderOnServer(
    /* @__PURE__ */ jsx(Component, { ...props }),
    renderContext,
    componentDebugName,
    renderOptions
  );
}
async function renderOnServer(elements, renderContext = bootStrapRenderContext(), debugName, renderOptions) {
  let html = await renderStreamToPromise(
    /* @__PURE__ */ jsx(ServerRenderContext.Provider, { value: renderContext, children: elements }),
    renderOptions
  );
  if (renderContext.messagesForBrowser.length > 0) {
    html = `${html}${scriptTagToLogServerMessages(
      renderContext.messagesForBrowser,
      `Server messages rendering: ${debugName}`
    )}`;
  }
  return { html, renderContext };
}
function getServerGlobalsToInject(environmentConfig, hsServerPageUrl, hsBasePath, prettyPrint, criticalDevErrors, includeNonces) {
  if (prettyPrint === void 0 && hsServerPageUrl && cmsComponents.isDebugUrlString) {
    prettyPrint = cmsComponents.isDebugUrlString(hsServerPageUrl);
  }
  const serializedJson = jsonStringifyAndEscapeForInlineJS(
    environmentConfig.toJSON(),
    { baseIndent: 6, prettyPrint }
  );
  const globals = [`window.__hsEnvConfig = ${serializedJson};`];
  if (hsServerPageUrl) {
    globals.push(
      `window.__hsServerPageUrl = ${jsonStringifyAndEscapeForInlineJS(
        hsServerPageUrl
      )};`
    );
  }
  if (hsBasePath) {
    globals.push(
      `window.__hsBasePath = ${jsonStringifyAndEscapeForInlineJS(hsBasePath)};`
    );
  }
  if (!environmentConfig.getIsDeployed() && (criticalDevErrors == null ? void 0 : criticalDevErrors.length)) {
    const firstCriticalDevError = criticalDevErrors[0];
    globals.push(`
      customElements.whenDefined('vite-error-overlay').then(() => {
        const ErrorOverlay = customElements.get('vite-error-overlay');
        const error = new Error(${jsonStringifyAndEscapeForInlineJS(
      firstCriticalDevError.message
    )});
        const overlay = new ErrorOverlay(error);

        document.body.appendChild(overlay);
      })
    `);
  }
  const nonceAttr = includeNonces && cmsComponents.SCRIPT_NONCE_PLACEHOLDER ? ` nonce="${cmsComponents.SCRIPT_NONCE_PLACEHOLDER}"` : "";
  return `
    <script type="text/javascript"${nonceAttr}>
      ${globals.join("\n      ")}
    </script>
      `;
}
function renderFieldsJSX(fieldsJSX) {
  let moduleJson;
  const outputCallback = (callbackJson) => {
    moduleJson = callbackJson;
  };
  renderToStaticMarkup(
    cloneElement(fieldsJSX, {
      outputCallback
    })
  );
  if (!moduleJson) {
    throw new Error("couldn't render module fields definition to fields.json");
  }
  return moduleJson;
}
function renderFieldsToJson(fields, moduleName) {
  let fieldsJSON;
  try {
    if (isValidElement(fields)) {
      fieldsJSON = renderFieldsJSX(fields);
    } else if (Array.isArray(fields)) {
      fieldsJSON = fields;
    } else {
      throw new Error(
        `Couldn't recognize \`fields\` value for module ${moduleName}`
      );
    }
    return fieldsJSON;
  } catch (e2) {
    e2.message = `Error when rendering fields for ${moduleName}: ${e2.message}`;
    throw e2;
  }
}
function DndAreaSlot(props) {
  return /* @__PURE__ */ jsx(
    "div",
    {
      suppressHydrationWarning: true,
      dangerouslySetInnerHTML: {
        __html: `<!-- hs-dnd-area-placeholder-${props.name} -->`
      }
    }
  );
}
function ModuleSlot(props) {
  return /* @__PURE__ */ jsx(
    "div",
    {
      suppressHydrationWarning: true,
      dangerouslySetInnerHTML: {
        __html: `<!-- hs-module-placeholder-${props.name} -->`
      }
    }
  );
}
function GlobalPartialSlot(props) {
  return /* @__PURE__ */ jsx(
    "div",
    {
      suppressHydrationWarning: true,
      dangerouslySetInnerHTML: {
        __html: `<!-- hs-global-partial-placeholder-${props.name} -->`
      }
    }
  );
}
export {
  COMPONENT_EXTENSIONS,
  CSS_LANGS_RE,
  DndAreaSlot,
  ENABLED_FEATURES_GATE_MAP,
  ENTRY_POINTS_PATH,
  GATES,
  GlobalPartialSlot,
  MODULE_FOLDER_PATH,
  ModuleSlot,
  TEMPLATE_FOLDER_PATH,
  VIRTUAL_CONFIG_SETUP,
  VIRTUAL_ISLAND_RUNTIME,
  areBuildHealthChecksEnabled,
  clientIslandEntryPlugin,
  collectCssInDev,
  collectCssModules,
  createIslandsGlobalJsForClientInDev,
  doHealthChecksFailTheBuild,
  escapeForInlineJS,
  findAllComponentsIn,
  findAllModulesInRoot,
  findAllPartialsInRoot,
  findCmsModules,
  getBaseAssetUrlFromBuild,
  getBuildInfo,
  getCMSAssetConfig,
  getCMSAssetConfigIfExists,
  getCombinedReactUrl,
  getComponentExtension,
  getEntryPointHash,
  getEntryPointHashWithIndexSuffix,
  getIslandRuntimeConfigUrl,
  getIslandUrls,
  getServerGlobalsToInject,
  getServerIncludePrebundleDepPatterns,
  hasComponentExtension,
  includesHublDataReference,
  isStorybookStory,
  isStylesheetAsset,
  isUngatedFor,
  jsonStringifyAndEscapeForInlineJS,
  namespaceModulePropsShape,
  noncePlaceholderPlugin,
  removeComponentExtension,
  removeIndexFromPath,
  removeIndexOrTrailingJsFromPath,
  renderComponentOnServer,
  renderFieldsToJson,
  renderOnServer,
  renderStreamToPromise,
  resolveIslandPlugin,
  resolveIslandToPlainModuleNoopPlugin,
  resolveIslandToPlainModulePlugin,
  scriptTagToLogServerMessages,
  serializeIslandDataForInlineScript,
  setIn,
  ungatedAtBuildTimeFor,
  virtualClientRenderIslandModuleId
};
